#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include "sys/socket.h"
//#include "arpa/inet.h"
#define debug_printfn(x)  printf("["__FILE__"][Line: %d][%s]: %s\r\n", __LINE__, __func__,x)
int get_localtm(char *str ,int  len);
int main() {
    printf("here is server !\n");
   int mSocket = socket(PF_INET,SOCK_DGRAM,0);
   if(mSocket==-1){
       debug_printfn("socket error");
       return -1;
   }
   struct sockaddr_in ser;
   ser.sin_family=AF_INET;
   ser.sin_port=htons(5000);
   ser.sin_addr.s_addr=inet_addr("127.0.0.1");

    //绑定套接字和地址结构
    debug_printfn("服务器：绑定套接字和地址结构");
    if(bind(mSocket,(struct sockaddr *)&ser,sizeof(ser)) == -1)
    {
        debug_printfn("bind error");
        return -1;
    }
    //处理数据
    debug_printfn("服务器：处理数据");







//    return (tv.tv_sec*1000 + tv.tv_usec/1000);
    while(1)
    {
        //接收客户端的串
        char buf[128] = {0};
        char timebuf[30] ={0};
        struct sockaddr_in cli;//用来输出客户端的地址结构
        socklen_t len = sizeof(cli);
        ssize_t size = recvfrom(mSocket,buf,sizeof(buf)-sizeof(buf[0]),0,(struct sockaddr*)&cli,&len);
        if(size == -1)
        {
            perror("recvfrom");
            return -1;
        }
        get_localtm(timebuf,30);
        printf("%s rev： %s \r\n",timebuf,buf);
        usleep(1000*100);


    }
    //关闭套接字
    printf("服务器：关闭套接字\n");
    close(mSocket);


    // clog_init("./log");//初始化日志模块，设置日志输出文件
 //   clog_set_log_size(1 * 1024 * 1024);//设置日志文件的最大值
 //   clog_set_log_level(EM_LOG_ERROR);//设置日志输出等级

//    clog_log(EM_LOG_ERROR, "CLOG ERROR.",1,"hello");
//    clog_log(EM_LOG_INFO,  "CLOG INFO.",1,"hello");
//    clog_log(EM_LOG_DEBUG, "CLOG DEBUG.",1,"hello");
 //   clog_exit();


    return 0;
}
/*
获取现在的时间并转换为格式化输出 例如 2017-05-24 22:42:08
建议str的长度不要小于30个字节
str 接收格式化之后的字符串数组
len str字符串数组的长度
 */
int get_localtm(char *str ,int  len){
    struct timeval tv;
    struct tm *tmp_time ;
    char  databuf[30]={0};
    if(len<30) return -1;
    gettimeofday(&tv, NULL);
    tmp_time = localtime(&tv.tv_sec);
    strftime(databuf, 30, "%Y-%m-%d %H:%M:%S", tmp_time);
    sprintf(str,"%s:%03d",databuf,(int)(tv.tv_usec/1000));
    return 1;
}